/**
 * Created by PanJiaChen on 16/11/18.
 */

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach((v) => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

// 判断是否移动端
export function isMobile() {
  var userAgent = navigator.userAgent.toLowerCase()
  if (
    userAgent.match(
      /(phone|pad|pod|iphone|ipod|ios|ipad|android|mobile|blackberry|iemobile|mqqbrowser|juc|fennec|wosbrowser|browserng|webos|symbian|windows phone|windows mobile|windows ce|ucweb|rv:1.2.3.4|midp)/i || /mobile/i.test(userAgent) || 'ontouchstart' in window || 'onorientationchange' in window
    )
  ) {
    return true
  } else {
    return false
  }
}

// 格式化日期时间
export function formatDate(value = Date.now(), format = 'Y-M-D h:m:s') {
  const formatNumber = (n) => `0${n}`.slice(-2)
  const date = new Date(value)
  const formatList = ['Y', 'M', 'D', 'h', 'm', 's']
  const resultList = []
  resultList.push(date.getFullYear().toString())
  resultList.push(formatNumber(date.getMonth() + 1))
  resultList.push(formatNumber(date.getDate()))
  resultList.push(formatNumber(date.getHours()))
  resultList.push(formatNumber(date.getMinutes()))
  resultList.push(formatNumber(date.getSeconds()))
  for (let i = 0; i < resultList.length; i++) {
    format = format.replace(formatList[i], resultList[i])
  }
  return format
}

// 获取几天前(后)几天的日期
export function getDay(day) {
  var today = new Date()
  var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day
  today.setTime(targetday_milliseconds) //注意，这行是关键代码
  return today
}

//周开始日期（周一为每周开始，周日为每周结束）
export function beginOfWeek(date) {
  let subDay = 0
  let weekDay = date.getDay()
  if (weekDay == 0) {
    //周天
    subDay = 6
  } else {
    subDay = weekDay - 1
  }
  let beginDateTime = date.getTime() - 86400000 * subDay
  let data = new Date(beginDateTime).getDate()
  let month = new Date(beginDateTime).getMonth() + 1
  let year = new Date(beginDateTime).getFullYear()
  return year + '-' + (month < 10 ? '0' + month : month) + '-' + (data < 10 ? '0' + data : data)
}
//周结束日期（周一为每周开始，周日为每周结束）
export function endOfWeek(date) {
  let weekDay = date.getDay()
  if (weekDay == 0) {
    //周天
    let data = date.getDate()
    let month = date.getMonth() + 1
    let year = date.getFullYear()
    return year + '-' + (month < 10 ? '0' + month : month) + '-' + (data < 10 ? '0' + data : data)
  } else {
    let addDay = 7 - weekDay
    let endDateTime = date.getTime() + 86400000 * addDay
    let data = new Date(endDateTime).getDate()
    let month = new Date(endDateTime).getMonth() + 1
    let year = new Date(endDateTime).getFullYear()
    return year + '-' + (month < 10 ? '0' + month : month) + '-' + (data < 10 ? '0' + data : data)
  }
}

// 本月起止时间
export function dateOfMonth() {
  var now = new Date()
  var nowYear = now.getFullYear() // 当前年
  let nowMonth = now.getMonth() + 1 // 当前月
  var endMonthDay = new Date(nowYear, nowMonth, 0).getDate() // 当前月的总天数
  var dateArr = [nowYear + '-' + nowMonth + '-01', nowYear + '-' + nowMonth + '-' + endMonthDay]
  return dateArr
}

// 上月起止时间
export function dateOfPrevMonth() {
  var now = new Date()
  var nowYear = now.getFullYear() // 当前年
  let nowMonth = now.getMonth() // 当前月
  if (nowMonth === 0) {
    nowYear--
    nowMonth = 12
  }
  var endMonthDay = new Date(nowYear, nowMonth, 0).getDate() // 当前月的总天数
  var dateArr = [nowYear + '-' + nowMonth + '-01', nowYear + '-' + nowMonth + '-' + endMonthDay]
  return dateArr
}

// FormData
export function formatFormData(info) {
  const formData = new FormData()
  for (let key in info) {
    formData.set(key, info[key])
  }
  return formData
}
